package com.xy.handler;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.tencentcloudapi.iai.v20200303.models.CreatePersonResponse;
import com.xy.constants.RabbitConstant;
import com.xy.entity.ViewerEntity;
import com.xy.request.QueueFaceDTO;
import com.xy.service.IViewerService;
import com.xy.tx.TxCommon;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.utils.BeanUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class QueueTxFace {
	private final IViewerService viewerService;
	@RabbitListener(queues = RabbitConstant.TOPIC_TENCENT_ADD_FACE_QUEUE)
	@RabbitHandler
	public void addFace(String jsonObject, Message message, Channel channel) {
		log.info("队列1 腾讯人脸注册，接收消息：{}",jsonObject);
		createPersonTx(JSONObject.parseObject(jsonObject, QueueFaceDTO.class));
	}
	@RabbitListener(queues = RabbitConstant.TOPIC_TENCENT_ADD_FACE_QUEUE)
	@RabbitHandler
	public void addFace1(String jsonObject, Message message, Channel channel) {
		log.info("队列1 腾讯人脸注册，接收消息：{}",jsonObject);
		createPersonTx(JSONObject.parseObject(jsonObject,QueueFaceDTO.class));
	}
	@RabbitListener(queues = RabbitConstant.TOPIC_TENCENT_DELETE_FACE_QUEUE)
	@RabbitHandler
	public void delFace(String jsonObject, Message message, Channel channel) {
		log.info("队列1 腾讯人脸删除，接收消息：{}",jsonObject);
		deletePersonTx(JSONObject.parseObject(jsonObject,QueueFaceDTO.class));
	}
	@RabbitListener(queues = RabbitConstant.TOPIC_TENCENT_DELETE_FACE_QUEUE)
	@RabbitHandler
	public void delFace1(String jsonObject, Message message, Channel channel) {
		log.info("队列1 腾讯人脸删除，接收消息：{}",jsonObject);
		deletePersonTx(JSONObject.parseObject(jsonObject,QueueFaceDTO.class));
	}

	/**
	 * 注册人脸
	 */
	public void createPersonTx(QueueFaceDTO queueFaceDTO){
//		try {
//			Thread.sleep(100);
//		} catch (InterruptedException e) {
//			throw new RuntimeException(e);
//		}
		CreatePersonResponse person = TxCommon.createPerson(queueFaceDTO.getPhotoUrl(), queueFaceDTO.getGroupId(), queueFaceDTO.getTicketId(), queueFaceDTO.getTicketName());

		if(person != null ){
			ViewerEntity ticketEntity = BeanUtil.newInstance(ViewerEntity.class);
			ticketEntity.setId(Long.parseLong(queueFaceDTO.getTicketId()));
			ticketEntity.setFaceRegister(0);
			viewerService.updateById(ticketEntity);
		}
	}

	/**
	 * 删除人脸
	 */
	public void deletePersonTx(QueueFaceDTO queueFaceDTO){
		TxCommon.deletePersonFromGroup(queueFaceDTO.getTicketId(),queueFaceDTO.getGroupId());
		TxCommon.createPerson(queueFaceDTO.getPhotoUrl(),queueFaceDTO.getGroupId(),queueFaceDTO.getTicketId(),queueFaceDTO.getTicketName());
	}
}
